/**
 * 
 */
package wong.board.client.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import wong.board.client.ui.BookmarksPresenter.View;
import wong.board.client.widgets.ContentContainer;
import wong.board.client.widgets.Link;
import wong.board.shared.ContentKeys;

import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;

/**
 * @author wong
 * 
 */
public class BookmarksView extends ContentContainer implements View {
	private HashMap<String, FlowPanel> groupPanels;
	private HashMap<String, List<String>> linkNames;

	public BookmarksView() {
		super(ContentKeys.Bookmarks.toString());
		addStyleName(boardCss.bookmarks());
	}

	@Override
	public void resetBookmarks() {
		getContent().clear();
	}

	@Override
	public void addLinks(String label, Set<String> linkNames, Map<String, String> links) {
		FlowPanel groupPanel = getGroupPanel(label, false);
		List<String> usedLinkNames = getLinkNames(label);
		for (String linkName : linkNames) {
			if (usedLinkNames.contains(linkName)) {
				// ignore
			} else {
				Link link = new Link(linkName, links.get(linkName));
				link.addStyleName(boardCss.bookmark());

				if (groupPanel == null) {
					groupPanel = getGroupPanel(label, true);
					groupPanel.add(link);
				} else {
					int index = getContent().getWidgetIndex(groupPanel) + usedLinkNames.size();
					getContent().insert(link, index);
				}
				usedLinkNames.add(linkName);
			}
		}
	}

	private FlowPanel getGroupPanel(String label, boolean create) {
		if (groupPanels == null) {
			if (!create) {
				return null;
			}
			groupPanels = new HashMap<String, FlowPanel>();
		}
		FlowPanel groupPanel = groupPanels.get(label);
		if (groupPanel == null && create) {
			groupPanel = new FlowPanel();
			groupPanel.setStyleName(boardCss.bookmarkGroup());
			Label groupLabel = new Label(label);
			groupLabel.setStyleName(boardCss.bookmarkGroupLabel());
			groupPanel.add(groupLabel);
			getContent().add(groupPanel);
			groupPanels.put(label, groupPanel);
		}
		return groupPanel;
	}

	private List<String> getLinkNames(String groupName) {
		if (linkNames == null) {
			linkNames = new HashMap<String, List<String>>();
		}
		List<String> names = linkNames.get(groupName);
		if (names == null) {
			names = new ArrayList<String>();
			linkNames.put(groupName, names);
		}
		return names;
	}

}
